﻿# encoding:utf-8
# 访问数据库 base
import pymysql
from wxpyImport import *

# 数据库结构体，为了能在方法内的修改返回到方法外
class dbData:
    def __init__(self):
        self.db = getDb()

# 连数据库
def getDb():
    try:
        # 打开数据库连接
        db = pymysql.connect(
            host='localhost',
            port=3306,
            user='root',
            passwd='0026888',
            db='wxpy',
            charset='utf8'
        )
    except Exception as e:
        dealException()
        logError('getDb err: '+str(e))
        return None
    
    logInfo('getDb: '+str(db))
    return db

def closeDb(dbd):
    try:
        logInfo('closeDb: '+str(dbd.db))
        dbd.db.close()
    except Exception as e:
        dealException()
        logError('closeDb err: '+str(e))

def getCursor(dbd, resetDb=False):
    try:
        return dbd.db.cursor()
    except Exception as e:
        dealException()
        logError('getCursor err: '+str(e))
        if resetDb:
            closeDb(dbd)
            dbd.db = getDb()
            return dbd.db.cursor()

# 读出的数据中包含列名 
def getCursorColName(dbd, resetDb=False):
    try:
        return dbd.db.cursor(cursor=pymysql.cursors.DictCursor)
    except Exception as e:
        dealException()
        logError('getCursorColName err: '+str(e))
        if resetDb:
            closeDb(dbd)
            dbd.db = getDb()
            return dbd.db.cursor(cursor=pymysql.cursors.DictCursor)

# 过滤掉字符串中的 xml 格式的 emoji
# 如：<span class="emoji emoji1f4a9"></span> -> emoji1f4a9
# return 替换后的字符串
def replaceEmojiXml(s):
    tmp = s.replace(r'<span class="emoji ','')
    return tmp.replace(r'"></span>', '')